<template>
  <div class="app-container">
    <div class="hor mg-b-10">
      <!--      <el-select v-model="filterLevel" placeholder="等级" clearable @change="onLevelChange"-->
      <!--                 class="">-->
      <!--        <el-option-->
      <!--          v-for="item in levelList"-->
      <!--          :key="item.value"-->
      <!--          :label="item.name"-->
      <!--          :value="item.value">-->
      <!--        </el-option>-->
      <!--      </el-select>-->
      <el-cascader
        size="min"
        class=""
        v-model="filterCompany"
        placeholder="请选择区域"
        :options="companyList"
        @change="onCompanyFilterChange"
        :props="{ expandTrigger: 'hover' }"
        clearable></el-cascader>
      <div class="pd-lr10"></div>
      <el-button type="primary" icon="el-icon-search" @click="onClickSearch()" class="">刷新
      </el-button>
      <div class="flex1"></div>
      <!--      <el-popconfirm-->
      <!--        class="mg-l-10"-->
      <!--        title="是否导出选中列？"-->
      <!--        icon="el-icon-info"-->
      <!--        iconColor="red"-->
      <!--        confirmButtonText='导出'-->
      <!--        @confirm="onClickExport()">-->
      <!--        <el-button slot="reference" type="warning">导出</el-button>-->
      <!--      </el-popconfirm>-->
      <el-button type="primary" icon="el-icon-plus" class="mg-l-10" v-has-permission
                 @click="onClickAdd()"></el-button>
      <el-button-group class="mg-l-10" v-has-permission>
        <el-tooltip class="item" effect="dark" content="删除后无法恢复" placement="bottom">
          <el-button type="danger" @click="onDeleteDialogShow = true ">
            <!--                           @click="isHadPermission(['budgetItemOperateAccess'])?onDeleteDialogShow = true:noPermissionHint();">-->
            删除
          </el-button>
        </el-tooltip>

      </el-button-group>
    </div>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="allList"
      :height="autoHeight"
      element-loading-text="Loading"
      @cell-click="onCellClick"
      @selection-change="handleSelectionChange"
      @row-click="onItemClick"
      @row-dblclick="onItemDoubleClick"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>

      <!--      <el-table-column align="center" label="ID" width="150">-->
      <!--        <template slot-scope="scope">-->
      <!--          {{ scope.row.id}}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="省份" width="200">
        <template slot-scope="scope">
          {{ scope.row.province}}
        </template>
      </el-table-column>
      <el-table-column label="城市" width="200">
        <template slot-scope="scope">
          {{ scope.row.city}}
        </template>
      </el-table-column>
      <el-table-column label="名称">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="总楼栋数" width="120">
        <template slot-scope="scope">
          {{ scope.row.louDongTotal }}
        </template>
      </el-table-column>
      <!--      <el-table-column label="已策划楼栋数(含相同楼型)">-->
      <!--        <template slot-scope="scope">{{ scope.row.louDongYiCeHua }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
<!--      <el-table-column label="总套数" width="120">-->
<!--        <template slot-scope="scope">{{ scope.row.zongTaoShu }}-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column class-name="status-col" label="操作" align="center" width="400">
        <template slot-scope="scope">
          <div class="hor">
            <div class="ver hor-center">
              <el-button type="warning" size="mini"
                         @click.stop="onClickLouDong(scope.row)">查看楼栋
              </el-button>
            </div>
            <div class="ver hor-center mg-l-20">
              <el-button type="info" class="pd-lr10" size="mini"
                         @click.stop="onClickView(scope.row)">编辑
              </el-button>
            </div>
            <div class="ver hor-center mg-l-20">

              <el-button type="danger" size="mini" :loading="onDeleteLoading"
                         @click.stop="onDeleteId=scope.row.id; onDeleteShow = true ">删除
              </el-button>
            </div>
          </div>

        </template>
      </el-table-column>
    </el-table>
    <div class="hor">
      <div class="flex1"></div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[20, 50, 100, 200]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="mg-t-10">
      </el-pagination>
    </div>
    <el-dialog
      title="信息"
      :visible.sync="infoDialogShow"
      width="700px"
      @open="onDialogOpen"
      center>
      <div class="ver match-width">
        <div class="ver" style="width: 600px;">
          <div class="hor ver-center ver-center mg-t-20">
            <div style="width: 100px;" class="font14 font-text-color-main-title">名称</div>
            <el-input class="flex1 font-text-color-main-title" style="width: 50px"
                      v-model="detail.name">
            </el-input>
          </div>
          <div class="hor mg-t-20 ver-center match-width">
            <div style="width: 100px;" class="font14 font-text-color-main-title">省市</div>
            <el-cascader
              class=""
              v-model="detail.city"
              placeholder="请选择省市"
              :options="regionList"
              @change="onRegionChange"
              :props="{ expandTrigger: 'hover' }"
              clearable></el-cascader>
          </div>
          <div class="hor mg-t-20 ver-center match-width">
            <!--            <div class="hor ver-center flex1">-->
            <!--              <div style="width: 100px;" class="font14 font-text-color-main-title">公司</div>-->
            <!--              <el-cascader-->
            <!--                class="flex1"-->
            <!--                v-model="detail.company.id"-->
            <!--                placeholder="请选择省市"-->
            <!--                :options="companyList"-->
            <!--                @change="onCompanyChange"-->
            <!--                :props="{ expandTrigger: 'hover' }"-->
            <!--                clearable></el-cascader>-->
            <!--            </div>-->
            <div class="hor ver-center flex1">
              <div style="width: 100px;" class="font14 font-text-color-main-title ">总楼栋数</div>
              <el-input-number class="flex1 font-text-color-main-title my-number"
                               style="width: 50px"
                               :min="0" :controls="false" :step="1" step-strictly disabled
                               v-model="detail.louDongTotal" placeholder="请输入"/>
            </div>
          </div>
          <div class="hor ver-center ver-center mg-t-20">
            <!--            <div class="hor ver-center flex1">-->
            <!--              <div style="width: 100px;" class="font14 font-text-color-main-title">已策划楼栋数（含相同楼型）-->
            <!--              </div>-->
            <!--              <el-input class="flex1 font-text-color-main-title" style="width: 50px"-->
            <!--                        v-model="detail.louDongYiCeHua">-->
            <!--              </el-input>-->
            <!--            </div>-->
            <div class="hor ver-center flex1">
              <div style="width: 100px;" class="font14 font-text-color-main-title">总套数</div>
              <el-input-number class="flex1 font-text-color-main-title my-number"
                               :min="0" :controls="false" :step="1" step-strictly disabled
                               v-model="detail.zongTaoShu" placeholder="请输入"/>
            </div>
          </div>
          <!--          <div class="hor ver-center ver-center mg-t-20">-->
          <!--            <div class="hor ver-center flex1">-->
          <!--              <div style="width: 100px;" class="font14 font-text-color-main-title">总车位数-->
          <!--              </div>-->
          <!--              <el-input-number class="flex1 font-text-color-main-title my-number"-->
          <!--                               :min="0" :controls="false" :step="1" step-strictly-->
          <!--                               v-model="detail.zongCheWeiShu" placeholder="请输入"/>-->
          <!--            </div>-->
          <!--          </div>-->

        </div>

        <div class="hor match-width ver-center hor-center mg-t-20">
          <el-button @click="infoDialogShow = false">取 消</el-button>
          <el-button type="primary" slot="reference" :loading="onSaveLoading" class="mg-l-10"
                     @click="onClickSave">保存
          </el-button>

        </div>

      </div>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="onDeleteDialogShow"
      width="30%">
      <span>删除后无法恢复</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onDeleteDialogShow = false">取消</el-button>
        <el-button type="danger" @click="batchDelete()" :loading="onDeleteLoading">删除</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="onDeleteShow"
      width="30%">
      <span>删除后无法恢复</span>
      <span slot="footer" class="dialog-footer">
                    <el-button @click="onDeleteShow = false">取消</el-button>
                    <el-button type="danger" @click="deleteById"
                               :loading="onDeleteLoading">删除</el-button>
                  </span>
    </el-dialog>
  </div>

</template>
<style>
</style>
<script>
  const request = require('@/api/project/project')
  const requestCompany = require('@/api/project/company')
  import {getCityData} from '@/js/cityData.js'

  let _this;
  export default {
    filters: {
      // statusFilter(status) {
      //   const statusMap = {
      //     published: 'success',
      //     draft: 'gray',
      //     deleted: 'danger'
      //   }
      //   return statusMap[status]
      // }
    },
    data() {
      return {
        allList: null,
        page: 1,
        size: 20,
        total: 0,
        autoHeight: 800,//根据屏幕高度自动计算的高度
        //筛选参数
        params: {
          flag: 1
        },
        filterLevel: '',
        selectRowList: [],
        onDeleteDialogShow: false,
        onDeleteLoading: false,
        onDeleteShow: false,
        onDeleteId: "",
        //信息窗口
        infoDialogShow: false,
        detail: {
          company: {
            id: ""
          }
        },
        onSaveLoading: false,
        regionList: [],
        companyOriginList: [],
        companyList: [],

        //选择地理位置
        pickMapShow: false,

        listLoading: true,
        filterCompany: null,
        biaoZhun: [
          {
            value: 1,
            text: '原浆地坪'
          },
          {
            value: 2,
            text: '非原浆地坪'
          }
        ],
      }
    }, beforeMount() {
      this.authHeight = document.body.scrollHeight - 190
      this.regionList = getCityData()
      //去掉第三级的信息
      for (let i = 0; i < this.regionList.length; i++) {
        if (this.regionList[i].children != null && this.regionList[i].children.length > 0) {
          for (let j = 0; j < this.regionList[i].children.length; j++) {
            this.regionList[i].children[j].children = null
          }
        }
      }

    }, mounted() {
      _this = this
      this.fetchData()
      this.getCompanyList();
    },
    created() {

    },
    methods: {
      fetchData() {
        this.listLoading = true
        const data = new FormData()
        for (var key in this.params) {//直接去除掉空值的对象
          if (this.isEmpty(this.params[key])) {
            delete this.params[key]
          }
        }

        data.append('params', JSON.stringify(this.params))
        data.append('page', this.page)
        data.append('size', this.size)

        const sortList = []
        sortList.push(
          {
            direction: 'desc',
            property: 'createTime'
          }
        )
        data.append('sortJsonStr', JSON.stringify(sortList))
        request.querySelf(data).then(response => {
          this.allList = response.data
          this.total = response.totalElements

          this.listLoading = false
        })
      }, prevent(e) {
        //获取键盘码
        var keynum = window.event ? e.keyCode : e.which;
        if (keynum == 189 || keynum == 190 || keynum == 109 || keynum == 110) {
          this.$message.warning('禁止输入小数以及负数')
          e.target.value = ''
        }
        if (keynum == 69) {
          this.$message.warning('不识别自然数e')
          e.target.value = ''
        }
      }, getCompanyList() {
        let params = {
          level: 1,
          flag: 1
        }
        const data = new FormData()

        data.append('params', JSON.stringify(params))
        data.append('page', 1)
        data.append('size', 99999)

        const sortList = []
        sortList.push(
          {
            direction: 'desc',
            property: 'createTime'
          }
        )
        data.append('sortJsonStr', JSON.stringify(sortList))

        requestCompany.getList(data).then(response => {
          let list = response.data
          this.companyList = []
          for (let i = 0; i < list.length; i++) {
            let data = {
              label: list[i].name,
              value: list[i].id,
              children: []
            };
            if (list[i].children != null || list[i].children.length == 0) {
              let children = list[i].children;
              for (let j = 0; j < children.length; j++) {
                data.children.push({
                  label: children[j].name,
                  value: children[j].id
                })
              }
            }
            this.companyList.push(data);
          }
          this.companyOriginList = list;
        })
      }, deleteById() {

        //通过id删除
        this.$message({
          message: '操作中',
          type: 'warning',
          duration: 1000
        })
        this.onDeleteLoading = true
        const data = new FormData()
        data.append('ids', [this.onDeleteId])
        request.batchDelete(data).then(response => {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 3000
          })
          this.onDeleteLoading = false
          this.onDeleteShow = false
          _this.fetchData()
        }).catch((e) => {
          this.onDeleteLoading = false
        })

      }, batchDelete() {
        const _this = this
        if (this.selectRowList == null || this.selectRowList.length == 0) {
          this.$message({
            message: '请选择对象',
            type: 'warning',
            duration: 1000
          })
          return
        }
        const array = []
        for (let i = 0; i < this.selectRowList.length; i++) {
          array.push(this.selectRowList[i].id)
        }
        const data = new FormData()
        data.append('ids', array)
        this.$message({
          message: '操作中',
          type: 'warning',
          duration: 1000
        })
        this.onDeleteLoading = true
        request.batchDelete(data).then(response => {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 3000
          })
          this.onDeleteLoading = false
          this.onDeleteDialogShow = false
          _this.fetchData()
        }).catch((e) => {
          this.onDeleteLoading = false
        })
      }
      , handleSizeChange(val) {
        this.size = val
        this.fetchData()
      }, handleCurrentChange(val) {
        this.page = val
        this.fetchData()
      }, onClickSearch() {//点击搜索
        if (!this.isEmpty(this.searchName)) {
          this.params['name_like'] = ('%' + this.searchName.trim() + '%')
        } else {
          this.params['name_like'] = ''
        }
        if (!this.isEmpty(this.searchType)) {
          this.params['type_like'] = ('%' + this.searchType.trim() + '%')
        } else {
          this.params['type_like'] = ''
        }
        if (this.filterCompany != null && this.filterCompany.length > 1) {
          this.params['company.id'] = this.filterCompany[1];
        } else {
          this.params['company.id'] = "";
        }


        this.fetchData()
      }, onInputClear(type) {//1.姓名
        if (type === 1) {
          this.searchName = ''
        } else if (type === 2) {
          this.searchType = ''
        }
        this.onClickSearch()

      }, handleSelectionChange(rowList) {//多选变化监听
        this.selectRowList = rowList
      }, onCellClick(row, column, cell, event) {
        if (column.type == 'selection') {
          this.$refs.table.toggleRowSelection(row)
        }
      }
      , onItemClick(row) {//单行点击
      }
      , onItemDoubleClick(row) {//单行双击
        this.onClickView(row)
      }
      , onClickAdd() {
        this.detail = {
          company: {}
        }
        this.infoDialogShow = true
      }, onDialogOpen() {
      }, onPositionDialogOpen() {
        this.$refs.map.initMap()
      }, onClickSave() {//点击保存
        if (this.detail.name == null || this.detail.name === "") {
          this.$message({
            message: '项目名称不能为空',
            type: 'warning',
            duration: 2000
          })
          return
        }
        this.enterVisible = false
        this.requestSave()
      }, onClickView(row) {
        this.infoDialogShow = true
        this.detail = row
        if (this.detail.company == null) {
          this.detail.company = {};
        }
      }, onClickLouDong(row) {
        const {href} = this.$router.resolve({
          path: "/fullScreen/loudong?selectProjectId=" + row.id + "&projectName=" + row.name
        })
        window.open(href, '_blank')//新窗口打开页面会卡死所以不开新窗口
        // window.location.href = href
      },
      onClickCanShu(row) {
        const {href} = this.$router.resolve({
          path: "/shice/parameterPlan?selectProjectId=" + row.id + "&projectName=" + row.name
        })
        // window.open(href, '_blank')//新窗口打开页面会卡死所以不开新窗口
        window.location.href = href
      }
      , requestSave() {
        this.onSaveLoading = true
        //把选择的权限赋值过去
        const data = new FormData()
        data.append('json', JSON.stringify(this.detail));
        request.saveByJson(data).then(response => {
          this.onSaveLoading = false
          this.infoDialogShow = false
          this.$message({
            message: '保存成功',
            type: 'success',
            duration: 2000
          })
          this.fetchData()
        }).catch((e) => {
          this.onSaveLoading = false
        })
      }, onLevelChange(val) {
        this.params.level = val + ''
        this.fetchData()
      }, onClickExport() {
        if (this.selectRowList == null || this.selectRowList.length == 0) {
          this.$message({
            message: '请选择对象',
            type: 'warning',
            duration: 1000
          })
          return
        }
        const array = []
        for (let i = 0; i < this.selectRowList.length; i++) {
          array.push(this.selectRowList[i].id)
        }
        const data = new FormData()
        data.append('ids', array)

        this.$message({
          message: '操作中',
          type: 'warning',
          duration: 1000
        })

        request.exportExcel(data).then(response => {
          console.log(response)
          this.$message({
            message: '导出成功',
            type: 'success',
            duration: 3000
          })
          window.open(response.data, '_blank');
        }).catch((e) => {

        })
      }, onAvatarChange(val) {//图片上传
        const isLt2M = val.size / 1024 / 1024 < 2

        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!')
          // console.log(this.shenghuoImgList)
          return false
        }
        this.uploadImg(val, 1)
      }, onAvatarRemove(val) {//图片移除
        console.log(val)

        this.deleteFile(_this.detail.img, function () {//成功
          // _this.avatar = null
          // _this.avatarUrl = null
          _this.detail.img = ''
        }, function () {//失败
        })
        return false
      }, uploadImg(val, type) {//根据类型上传单图片 1.头像 2.身份证正面 3.身份证反面 4.房产证 5.行驶证
        this.$message('上传中')
        this.uploadSingleFile(val.raw, function (key, url) {
          //分类型处理
          switch (type) {
            case 1:
              _this.detail.img = key
              _this.detail.imgUrl = url + '?imageView2/1/w/400/h/300'
              // _this.img = key
              // _this.imgUrl = url + '?imageView2/1/w/200/h/200'
              break
            // case 2:
            //   _this.userDetail.userDetail.idCardPathFront = key
            //   _this.idCardFont = key
            //   _this.idCardFontUrl = url + '?imageView2/1/w/200/h/200'
            //   break
          }

          console.log('上传成功  ' + key + '   ' + url)
          _this.$message({
            message: '上传成功',
            type: 'success'
          })
          console.log(_this.detail)
          // console.log(_this.shenghuoImgList)
        }, function (percent) {
          // vant.Notify({type: 'success', message: '上传中'});
          console.log(percent)
        }, function (res) {
          // vant.Notify({type: 'danger', message: '上传图片失败' + res});
          console.log(res)
          _this.$message({
            message: '上传失败',
            type: 'error'
          })
        })
      }, onMapCancel() {
        this.pickMapShow = false;
      }, onMapEnter(item) {
        // console.log(item);
        this.pickMapShow = false;
        this.detail.lat = item.lat
        this.detail.lng = item.lng
        this.detail.address = item.value
        // this.model.companyCardDetailList[0].address = item.name;
        // this.model.companyCardDetailList[0].gcj02Lat = item.lat;
        // this.model.companyCardDetailList[0].gcj02Lng = item.lng;
      }, onRegionChange(val) {
        const one = val[0]
        const two = val[1]

        this.detail.province = one;
        this.detail.city = two;
        //循环找到选择的类型
        // for (let i = 0; i < this.regionList.length; i++) {
        //   if (oneId == this.regionList[i].id) {
        //     for (let j = 0; j < this.regionList[i].children.length; j++) {
        //       if (twoId == this.regionList[i].children[j].id) {
        //         this.detail.articleType = this.regionList[i].children[j];
        //         break;
        //       }
        //     }
        //   }
        // }
      }, onCompanyChange(val) {
        const one = val[0]
        const two = val[1]

        if (two == null || two == undefined) {
          return
        }
        console.log(two);
        //找到对应的公司
        for (let i = 0; i < this.companyOriginList.length; i++) {
          let children = this.companyOriginList[i].children;
          for (let j = 0; j < children.length; j++) {
            if (two == children[j].id) {
              this.detail.company.id = two;
              this.detail.company.province = children[j].province;
              this.detail.company.city = children[j].city;
              console.log(this.detail)
            }
          }
        }

        //循环找到选择的类型
        // for (let i = 0; i < this.regionList.length; i++) {
        //   if (oneId == this.regionList[i].id) {
        //     for (let j = 0; j < this.regionList[i].children.length; j++) {
        //       if (twoId == this.regionList[i].children[j].id) {
        //         this.detail.articleType = this.regionList[i].children[j];
        //         break;
        //       }
        //     }
        //   }
        // }
      },
      onCompanyFilterChange(val) {
        console.log(val)
        const one = val[0]
        const two = val[1]

        console.log(one, two)
        this.onClickSearch()
      },

    }
  }
</script>
<style>
  .svg-icon {
    width: 1em;
    height: 1em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
  }

  .svg-external-icon {
    background-color: currentColor;
    mask-size: cover !important;
    display: inline-block;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 400px;
    height: 300px;
    line-height: 300px;
    text-align: center;
  }

  /*清除type=number的上下箭头*/
  /* 在Chrome浏览器下 */
  input::-webkit-outer-spin-button, input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }

  /* 在Firefox浏览器下 */
  input[type="number"] {
    -moz-appearance: textfield;
  }

  .my-number .el-input .el-input__inner {
    text-align: left;
  }
</style>
